#include "canvas.h"
#include <GL/gl.h>
#include <string>

using namespace std;

struct image
{
	int ident;
	float x, y, xsize, ysize;
	string* tex;
	image* next;
};

StillImage::StillImage(float _x, float _y, float _xsize, float _ysize, string tex) :
texture(tex)
{
	x = _x;
	y = _y;
	xsize = _xsize;
	ysize = _ysize;
}

StillImage::~StillImage()
{
}

void StillImage::Render()
{
	float x1 = x;
	float y1 = y;
	float x2 = x1 + xsize;
	float y2 = y1 + ysize;

	scale s = BindImageTexture(texture);

	glBegin(GL_QUADS);

	glTexCoord2f(0.0, 0.0);
	glVertex2f(x1, y1);

	glTexCoord2f(0.0, s.yscale);
	glVertex2f(x1, y2);

	glTexCoord2f(s.xscale, s.yscale);
	glVertex2f(x2, y2);

	glTexCoord2f(s.xscale, 0.0);
	glVertex2f(x2, y1);

	glEnd();
	glDisable(GL_TEXTURE_2D);
}

Canvas::Canvas() : image_list(0)
{
	minx = -1;
	miny = -1;
	maxx = 1;
	maxy = 1;
}

Canvas::~Canvas()
{
	for(list<StillImage*>::iterator i = image_list.begin(); i != image_list.end(); i++)
	{
		delete *i;
	}
}

StillImage* Canvas::AddImage(float x, float y, float xsize, float ysize, string tex)
{
	StillImage* i = new StillImage(x, y, xsize, ysize, tex);
	image_list.push_back(i);
	return i;
}

void Canvas::DelImage(StillImage* ident)
{
	image_list.remove(ident);
}

void Canvas::SetSize(float x1, float y1, float x2, float y2)
{
	minx = x1;
	miny = y1;
	maxx = x2;
	maxy = y2;
}

void Canvas::Render()
{
	glMatrixMode(GL_PROJECTION_MATRIX);
	glOrtho(minx, maxx, miny, maxy, -1, 1);
	glMatrixMode(GL_MODELVIEW_MATRIX);
	for(list<StillImage*>::iterator i = image_list.begin(); i != image_list.end(); i++)
	{
		(*i)->Render();
	}

	float x1 = 0;
	float y1 = 0;
	float x2 = 200;
	float y2 = 30;

	glEnable(GL_TEXTURE_2D);
	scale s = BindTextTexture("Tesxting");
	glBegin(GL_QUADS);

	glTexCoord2f(0.0, s.yscale);
	glVertex2f(x1, y1);
	
	glTexCoord2f(0.0, 0.0);
	glVertex2f(x1, y2);

	glTexCoord2f(s.xscale, 0.0);
	glVertex2f(x2, y2);

	glTexCoord2f(s.xscale, s.yscale);
	glVertex2f(x2, y1);

	glEnd();
	glDisable(GL_TEXTURE_2D);
}

